import msgVue from "../pages/msg/msg.vue";

/**
 * 查询数量
 * @param {Object} db
 * @param {Object} table
 * @param {Object} index
 * @param {Object} keyRange
 */
export function countByIndex(db, table, index, query) {
	return queryByIndexCondition(db, table, index, query).then(data => {
		return data.length;
	})
}

/**
 * 
 * @param {Object} db 数据库的名称
 * @param {Object} table 表的名称
 * @param {Object} index 索引的名称
 * @param {Object} keyRange 键（key）的范围
 * @param {Object} condi    查询对应的其他过滤条件。
 * @param {*} cnt  查询对应的数量
 */
export function queryByIndexCondition(db, table, index, query, direct, condi, condi1, offset, limit) {
	console.log("index ", index);
	return new Promise((resolve, reject) => {
		var transaction = db.transaction(table, 'readonly');
		var objectStore = transaction.objectStore(table);
		// 获取type索引
		var typeIndex = objectStore.index(index);
		// 基于type索引打开游标，查找type为1的记录
		var cursorRequest = null;

		cursorRequest = typeIndex.openCursor(query, direct);

		let resultArr = []
		cursorRequest.onsuccess = function(event) {
			//一直回调
			let cursor = event.target.result
			if (cursor) {
				let result = cursor.value
				resultArr.push(result)
				cursor.continue()
			} else {
				console.log("总数据", resultArr.length);
				if (condi || condi1) {
					//过滤
					resultArr = resultArr.filter(item => {
						let cc = [];
						let cc1 = [];
						if (condi) {
							for (const key in condi) {
								if (item[key] == condi[key]) {
									cc.push(true);
								} else {
									cc.push(false);
								}
							}
						}
						if (condi1) {
							for (const key in condi1) {
								if (item[key] == condi1[key]) {
									cc1.push(true);
								} else {
									cc1.push(false);
								}
							}
						}

						let bool = cc.filter(item => item == false).length == 0 ||
							cc1.filter(item => item == false).length == 0;

						return bool;
					})
				}

				console.log("过滤后", resultArr.length);
				//处理分页
				if (offset != null && limit != null) {
					resultArr = resultArr.slice(offset, offset + limit);
				}

				resolve(resultArr)
			}
		};
		cursorRequest.onerror = function(event) {
			console.log('查询出错：', event.target.error);
			reject(event.target.error.message)
		};
	});
}


/**
 * 添加记录
 */
export function addHistoryRecord(msg) {
	return dbInit().then(db => {
		const transaction = db.transaction(['chathistory'], 'readwrite'); // 使用 'readwrite' 权限
		const objectStore = transaction.objectStore('chathistory');
		if (msg.msgId == null) {
			console.error("保存会话失败");
			return;
		}
		objectStore.put(msg);
	})
}

/**
 * @param {Object} cnt
 * 查询历史记录
 */
export function queryHistoryRecord(offset, limit, type, recerId) {
	return dbInit().then(db => {
		let index = "msgIdIndex";
		let query = null;
		let direct = "prev";
		let cond = null;
		let cond1 = null;
		let table = "chathistory";
		if (type == 2) {
			cond = {
				groupId: recerId,
				type: type,
			};
		} else {
			//接收人是外人 发送的
			cond = {
				receiverId: recerId,
				type: type,
			};
			//接收人是自己 并且发送人是外人
			let userId = uni.getStorageSync("login:userid");
			cond1 = {
				receiverId: userId,
				type: type,
				senderId: recerId,
			};

		}
		return queryByIndexCondition(db, table, index, query, direct, cond, cond1, offset, limit);
	})

}





export function queryChatList() {
	let table = "chatlist";
	return dbInit().then(db => {
		return queryByIndexCondition(db, table, "dateIndex", null, "prev");
	})
}

//判断会话是否存在，存在更新时间，不存在添加
export function saveChatList(item, type) {
	return dbInit().then(db => {
		let receiverId = null;
		let username = null;
		if (type == 2) {
			receiverId = item.groupId;
			username = item.groupName;
		} else {
			receiverId = item.userId;
			username = item.username;
		}
		return queryChatList(db).then(data => {
			let rst = data.filter(item => {
				return item.type == type && item.receiverId == receiverId;
			});
			const transaction = db.transaction(['chatlist'], 'readwrite'); // 使用 'readwrite' 权限
			const objectStore = transaction.objectStore('chatlist');
			if (rst.length > 0) {
				//存在，更新时间
				console.log(rst);
				let lastDate = new Date().getTime();
				let c = rst[0];
				c.noread = 0; //未读数量置为0
				c.lastDate = lastDate;
				objectStore.put(c);

			} else {
				let id = new Date().getTime();
				let record = {
					id: id,
					type: type,
					receiverId: receiverId,
					lastDate: id,
					name: username,
					noread: 0, //未读数0，
					lastTxt: null, //最后一条消息
				}
				objectStore.put(record);
			}

			//发送消息
			uni.$emit("chatlistflush", true);

			return true;
		});
	})
}

/**
 * 直接保存一条新的会话信息
 */
export function saveChatDirect(chatUser) {
	return dbInit().then(db => {
		const transaction = db.transaction(['chatlist'], 'readwrite'); // 使用 'readwrite' 权限
		const objectStore = transaction.objectStore('chatlist');
		objectStore.put(chatUser);
		return chatUser;
	})
}

export function msg2ChatUser(msgData) {
	let receiverId = null;
	let username = null;
	if (msgData.type == 2) {
		receiverId = msgData.groupId;
		username = msgData.groupName;
	} else {
		receiverId = msgData.senderId;
		username = msgData.senderName;
	}

	console.log("保存", msgData);
	let id = new Date().getTime();
	let record = {
		id: id,
		type: msgData.type,
		receiverId: receiverId,
		lastDate: id,
		name: username,
		noread: 1, //未读数0，
		lastTxt: msgData.msgContent, //最后一条消息
	}
	return record;
}

export function updateChatDirect(chatItem, msgContent) {
	return dbInit().then(db => {
		const transaction = db.transaction(['chatlist'], 'readwrite'); // 使用 'readwrite' 权限
		const objectStore = transaction.objectStore('chatlist');
		//更新未读数量+上一次的文本
		//判断当前页面
		let page = getCurrentPages();
		console.log("页面堆栈", page);

		if (chatItem.noread == null) {
			chatItem.noread = 0;
		}
		console.log("当前会话更新", chatItem)
		chatItem.noread = chatItem.noread + 1;
		chatItem.lastTxt = msgContent;
		objectStore.put(chatItem);
		return 1;
	})
}

export function updateChatDirectMsg(chatItem, msg) {
	return dbInit().then(db => {
		const transaction = db.transaction(['chatlist'], 'readwrite'); // 使用 'readwrite' 权限
		const objectStore = transaction.objectStore('chatlist');
		console.log("当前会话更新", chatItem)
		chatItem.lastTxt = msg;
		objectStore.put(chatItem);
		return 1;
	})
}



export function dbInit(initDb = false) {
	return new Promise((resolve, reject) => {
		let request = indexedDB.open('im', 4);
		//数据库成功打开时
		request.onsuccess = function(event) {
			let db = event.target.result;
			console.log('数据库已打开', db);
			resolve(db);
		};
		//初始化索引
		if (initDb) {
			initDbIndex(request);
		}
	});
}

export function initDbIndex(request) {
	//首次创建或者版本更新	
	request.onupgradeneeded = function(event) {
		let db = event.target.result;
		let chatlist = db.createObjectStore('chatlist', {
			keyPath: 'id'
		});
		chatlist.createIndex('typeIndex', 'type', {
			unique: false
		});
		chatlist.createIndex('receiverIdIndex', 'receiverId', {
			unique: false
		});
		//最后打开的时间
		chatlist.createIndex('dateIndex', 'lastDate', {
			unique: false
		});


		//创建历史数据记录
		// 创建对象仓库
		var chathistory = db.createObjectStore('chathistory', {
			keyPath: 'msgId'
		});
		chathistory.createIndex('msgIdIndex', 'msgId', {
			unique: true
		});
		// 创建各个索引
		chathistory.createIndex('typeIndex', 'type', {
			unique: false
		});
		chathistory.createIndex('groupIdIndex', 'groupId', {
			unique: false
		});
		chathistory.createIndex('receiverIdIndex', 'receiverId', {
			unique: false
		});

	};
}


/**
 * @param {Object} timestamp
 * 时间戳格式化为时间
 */
export function timestamp2DateTime(timestamp) {
	// 获取当前时间戳（单位：毫秒），也可以替换成其他具体的时间戳数值
	const date = new Date(timestamp);

	const year = date.getFullYear();
	const month = date.getMonth() + 1; // 月份是从0开始计数的，所以要加1
	const day = date.getDate();
	const hours = date.getHours();
	const minutes = date.getMinutes();
	const seconds = date.getSeconds();

	const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	return formattedTime;
}


export default {
	queryHistoryRecord,
	countByIndex,
	queryChatList,
	dbInit,
}